package server.doc.xml;

import java.io.*;
import org.dom4j.*;
import org.dom4j.io.*;

public abstract class XMLDoc {
	private String fileName;
	
	public XMLDoc(String name) {
		fileName = name;
/*		SAXReader reader = new SAXReader();
		try {
			xmlFile = reader.read(new File(fileName));
		} catch (Exception e) {
			newFile();
		}*/
	}
	
	synchronized public Document getXML() {
		SAXReader reader = new SAXReader();
		Document xmlFile = null;
		File file = new File(fileName);
		if (file.exists()) {
			try {
				xmlFile = reader.read(file);
			} catch (Exception e) {
				System.err.println("Error while reading XML file \"" + fileName + "\", now create a backup and reset.");
				File backup = new File(fileName + ".bak");
				if (backup.exists())
					backup.delete();
				file.renameTo(backup);
				writeFile(initXML());
				try {
					xmlFile = reader.read(file);
				} catch (Exception fatal) {
					System.err.println("fatal error while processing XML file");
				}
			}
		} else {
			writeFile(initXML());	// file doesn't exist, create a new one and initialize
			try {
				xmlFile = reader.read(file);
			} catch (Exception e) {
				System.out.println("fatal error while processing XML file");
			}
		}
		return xmlFile;
	}
	
	synchronized public void writeFile(Document xml)
	{
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
			writer.write(xml);
			writer.close();
		} catch (Exception e) {
			System.err.println("Cannot create xml file \"" + fileName + "\"");
		}
	}
	
	public abstract Document initXML();
/*	public abstract void addEntry(MvcModel entry);
	public abstract void deleteEntry(MvcModel entry);
	public abstract void updateEntry(MvcModel entry);*/
}
